package www.openteam.com.transformer;

import android.util.Log;

import rx.Observable;
import rx.exceptions.Exceptions;
import rx.functions.Func1;
import www.openteam.com.base.BaseHttpResult;
import www.openteam.com.exception.ErrorType;
import www.openteam.com.exception.ExceptionEngine;
import www.openteam.com.exception.ServerException;

/**
 * Created by kylin on 2016/12/19.
 */

public class ErrorTransformer<T> implements Observable.Transformer<BaseHttpResult<T>,T> {

    private static ErrorTransformer errorTransformer;
    private final String TAG=ErrorTransformer.class.getSimpleName();

    @Override
    public Observable<T> call(Observable<BaseHttpResult<T>> responseObservable) {
        return responseObservable.map(new Func1<BaseHttpResult<T>, T>() {
            @Override
            public T call(BaseHttpResult<T> httpResult) {

                if (httpResult == null) {
                    throw new ServerException(ErrorType.EMPTY_BEAN, "解析对象为空");
                }
                Log.d(TAG, "call: "+httpResult.toString());
                if (httpResult.getStatus() != ErrorType.SUCCESS) {
                    Log.d(TAG, "call: "+httpResult.getStatus());
                    throw new ServerException(httpResult.getStatus(), httpResult.getMessage());
                }
                return httpResult.getData();
            }
        }).onErrorResumeNext(new Func1<Throwable, Observable<? extends T>>() {
            @Override
            public Observable<? extends T> call(Throwable throwable) {
                //ExceptionEngine 为处理异常的驱动器
                throwable.printStackTrace();
                Log.d(TAG, "call: thr"+throwable.toString());
                return Observable.error(ExceptionEngine.handleException(throwable));
            }
        });
    }

    public static <T> ErrorTransformer<T> getInstanse(){
            if (errorTransformer ==  null){

                synchronized (ErrorTransformer.class){
                    if (errorTransformer ==null){
                        errorTransformer =new ErrorTransformer<>();

                    }
                }
            }
        return errorTransformer;
    }
}
